% 仿真qpsk调制的基带数字信号经过awgn信道，通过m序列进行扩频和解扩，计算误码率和误符号率
clear all;              %清空工作区变量
nSamp = 8;              %矩形脉冲的取样点数
numSymb = 1000000;      %每种SNR下的传输的符号数
M=4;                    %QPSK的符号类型数
SNR=-30:3;              %SNR的范围
grayencod=[0 1 3 2];    %Gray编码格式

% 生成13位barker序列
barker = [1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1];

% 循环遍历每种SNR
for ii=1:length(SNR)
    msg=randsrc(1,numSymb,0:3);             %产生发送符号
    msg_gr=grayencod(msg+1);                %进行Gray编码映射
    msg_tx=pskmod(msg_gr,M);                %QPSK调制
    msg_tx_sp = zeros(1,length(msg_tx)*length(barker)); %初始化扩频后的信号
    for j = 1:length(msg_tx)
        msg_tx_sp((j-1)*length(barker)+1:j*length(barker)) = barker.*msg_tx(j); %扩频
    end
    msg_tx_sp = rectpulse(msg_tx_sp,nSamp); %矩形脉冲成形
    msg_rx=awgn(msg_tx_sp,SNR(ii),'measured'); %通过AWGN信道
    msg_rx_down = intdump(msg_rx,nSamp);    %匹配滤波相干解调    
    msg_rx_down_sp = zeros(1,length(msg_rx_down)/length(barker)); %初始化扩频后的接收信号
    for j = 1:length(msg_rx_down_sp)
        msg_rx_down_sp(j) = sum(msg_rx_down((j-1)*length(barker)+1:j*length(barker)).*barker); %去扩频
    end
    msg_gr_demod = pskdemod(msg_rx_down_sp,M); %QPSK解调
    [dummy, graydecod] = sort(grayencod); 
    graydecod = graydecod - 1;
    msg_demod = graydecod(msg_gr_demod+1); %Gray编码逆映射
    [errorBit, BER(ii)] = biterr(msg, msg_demod, log2(M)); %计算BER
    [errorSym, SER(ii)] = symerr(msg, msg_demod);          %计算SER
end

% 画出发射信号和接收信号的星座图
scatterplot(msg_tx(1:100))                  
title('发射信号星座图')
xlabel('同相分量')
ylabel('正交分量')
scatterplot(msg_rx_down_sp(1:100))                  
title('接收信号星座图')
xlabel('同相分量')
ylabel('正交分量')

% 画出BER和SER随SNR变化的曲线
figure
semilogy(SNR,BER,'-o',SNR,SER,'-*')       
legend('BER','SER')
title('QPSK在AWGN信道下的性能')
xlabel('信噪比（dB）')
ylabel('误符号率和误比特率')